/*
 * 英才汇硕信息科技有限公司 拥有本软件版权 2021 并保留所有权利。
 * Copyright 2021, YCHS Information&Science Techology Co.,Ltd,
 * All right reserved.
 */
package com.ychs.lawyerback.aspect;

import com.ychs.lawyerback.annotation.RequiredPermission;
import com.ychs.lawyerback.common.ResultCode;
import com.ychs.lawyerback.exception.BussinessException;
import com.ychs.lawyerback.vo.LoginUserVo;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * @author mayujing
 * @version 1.0
 */
@Aspect
@Component
public class PermissionAspect {

    @Before("@annotation(com.ychs.lawyerback.annotation.RequiredPermission)")
    public Object before(JoinPoint jp) {
        //获取request请求获取里面的当前登录的用户信息
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        LoginUserVo loginUserVo = (LoginUserVo) request.getAttribute("loginUserVo");

        //获取访问目标方法的注解
        MethodSignature signature = (MethodSignature) jp.getSignature();
        RequiredPermission annotation = signature.getMethod().getAnnotation(RequiredPermission.class);
        String value = annotation.value();
        if (!loginUserVo.getPermission().contains(value)) {
            throw new BussinessException(ResultCode.METHOD_NOT_PRIVILEGE);
        }
        return value;
    }


}
